package com.code4j.tree;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

public class Controller implements ActionListener{

	List<Action> actions = new ArrayList<Action>();

	class Action {
		String actionCommand;
		int keyChar;
		String tips;
	}

	public final static String ACTION_COMMAND_SUFFIX = "Command";
	public final static String KEY_CAHR_SUFFIX = "Key";
	public final static String TIPS_SUFFIX = "Tip";

	public Controller() {
		try {
			Properties prop = new Properties();
			prop.load(new FileReader("action.properties"));

			String string = prop.getProperty("actions");
			for (String str : string.split("\\s")) {
				String actionCommand = prop.getProperty(str + ACTION_COMMAND_SUFFIX);
				String strChar = prop.getProperty(str + KEY_CAHR_SUFFIX);
				String tips = prop.getProperty(str + TIPS_SUFFIX);
				Action action = new Action();
				action.actionCommand = actionCommand;
				action.keyChar = strChar.toCharArray()[0];
				action.tips = tips;
				actions.add(action);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * model
	 */
	BinaryTree tree;

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("add")) {
			String c = JOptionPane.showInputDialog("Add a new node:");
			if (c != null && !"".equals(c)) {
				//tree.addNode(c);
				tree.insert(Integer.parseInt(c));
				tree.refreshTree();
			}
		} else if (e.getActionCommand().equals("random")) {
			TreeBuilder builder = new TreeBuilder();
			//tree = builder.getTree();
			tree.clearAll();
			builder.fillBinaryTree(tree);
			tree.refreshTree();
		} else if (e.getActionCommand().equals("print")) {
			tree.preOrder();
		}else if(e.getActionCommand().equals("height")){
			tree.height();
		}else if(e.getActionCommand().equals("dfs")){
			tree.dfs();
		}
	}

	public void setTree(BinaryTree tree) {
		this.tree = tree;
	}

	public void SetView(BinaryTreeView view) {
		for (Action action : actions) {
			view.registerKeyboardAction(this, action.actionCommand, KeyStroke.getKeyStroke(action.keyChar, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
		}
	}

	public void setTipsView(JLabel label) {
		StringBuilder sb = new StringBuilder();
		sb.append("<html>");
		for (Action action : actions) {
			char ch = (char) (action.keyChar - 97 + 'a');
			sb.append("press \"" + ch + "\" " + action.tips + "<br>");
		}
		sb.append("</html>");
		label.setText(sb.toString());
	}

}
